package com.example.core.filter.mock;

import com.example.common.config.Rule;
import com.example.common.util.JSONUtil;
import com.example.core.context.GatewayContext;
import com.example.core.filter.Filter;
import com.example.core.filter.FilterAspect;
import com.example.core.helper.ResponseHelper;
import com.example.core.response.GatewayResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

import static com.example.common.constants.FilterConst.*;

/**
 * @Author Peng Yisheng
 * @Date 2024/12/10 16:34
 * @Description Mock响应过滤器
 */
@Slf4j
@FilterAspect(id = MOCK_FILTER_ID,
        name = MOCK_FILTER_NAME,
        order = MOCK_FILTER_ORDER)
public class MockFilter implements Filter {
    @Override
    public void doFilter(GatewayContext ctx) throws Exception {
        Rule.FilterConfig config = ctx.getRule().getFilterConfig(MOCK_FILTER_ID);
        if (config == null) {
            return;
        }

        Map<String, String> map = JSONUtil.parse(config.getConfig(), Map.class);
        // "config": { "GET /http/ping": "mock" }
        String value = map.get(ctx.getRequest().getMethod().name() + " " + ctx.getRequest().getPath());
        if (value != null) {
            // 这里用的是json格式响应，非原始响应格式。原始响应格式在data中
            ctx.setResponse(GatewayResponse.buildGatewayResponse(value));
            ctx.written();
            ResponseHelper.writeResponse(ctx);
            log.info("mock {} {} {}", ctx.getRequest().getMethod(), ctx.getRequest().getPath(), value);
            ctx.terminated();
        }
    }
}
